<template>
	<view v-if="hasToken" class="content">
		<tm-navbar title="" hideHome>
			<template v-slot:left>
				<view class="pl-24 fd-r">
					<text class="fs-28 c-red fw-b">购物车</text>
				</view>
			</template>

			<view v-if="cartList.length > 0" class="flex1 fd-r jc-fe">
				<button
					v-if="isManage"
					class="btn-red-text mx-0"
					hover-class="btn-hover"
					@click="() => (isManage = false)"
				>
					完成
				</button>
				<button
					v-else
					class="btn-red-text mx-0"
					hover-class="btn-hover"
					@click="() => (isManage = true)"
				>
					管理
				</button>
			</view>
		</tm-navbar>

		<view v-if="cartList.length == 0" class="pt-100 fd-c ai-c">
			<image
				class="w-200 h-200"
				src="@/static/cart-empty.png"
				mode=""
			></image>
			<text class="mt-16 fs-28 c-grey">您的购物车竟然是空的</text>
		</view>

		<block v-for="item in cartList" :key="item.id">
			<view class="z-card px-24">
				<view class="py-16 fd-r">
					<checkbox
						color="#c8161d"
						:checked="item.checked"
						style="transform: scale(0.7)"
						@click="HCheckChange(item)"
					/>
					<text>{{ item.storeName }}</text>
				</view>
				<view class="divider"></view>
				<block v-for="cart in item.list" :key="cart.id">
					<view class="py-24 fd-r">
						<checkbox
							color="#c8161d"
							:checked="cart.checked"
							style="transform: scale(0.7)"
							@click="HSubCheckChange(cart)"
						/>
						<image
							class="w-100 h-100 rd-8"
							:src="cart.sku.img"
							mode="aspectFill"
							@click="HGotoDetail(cart.mallGood.id, cart.sku.id)"
						></image>
						<view class="flex1 pl-24 fd-c ai-s">
							<view class="pb-12 fd-r">
								<text class="fs-28">{{ cart.sku.name }}</text>
							</view>
							<view class="fd-r" @click="HSpecChange(cart)">
								<view class="px-16 py-8 rd-8 fd-r bg-e0e0e0">
									<text class="flex1 fs-20 lines1 mr-12">
										{{ cart.sku.spec1 }}
										{{ cart.sku.spec2 }}
									</text>
									<tm-icon
										name="tmicon-angle-right"
										:fontSize="16"
									></tm-icon>
								</view>
							</view>
							<view class="pt-12 fd-r jc-fe">
								<text class="fs-24 c-red">￥</text>
								<text class="flex1 fs-32 c-red">
									{{ cart.sku.price }}
								</text>
								<tm-stepper
									v-model="cart.quantity"
									color="red"
									bgColor="red"
									:step="1"
									circular
									:defaultValue="cart.quantity"
									:min="1"
									:max="cart.sku.stock"
									@change="HCountChange($event, cart)"
								></tm-stepper>
							</view>
							<text v-if="cart.price > cart.sku.price" class="fs-24 c-red">
								比加入时降￥{{ cart.price - cart.sku.price }}
							</text>
						</view>
					</view>
				</block>
			</view>
		</block>

		<view class="pt-24 fd-r jc-c">
			<text class="fs-28 fw-b c-red">猜你喜欢</text>
		</view>

		<view class="px-24">
			<tm-waterfall ref="wall" :width="702" :gutter="24">
				<tm-waterfall-item
					:img="item.mainImg"
					v-for="(item, index) in goodList"
					:key="item.id"
					@click="HGotoDetail(item.id)"
				>
					<view class="pt-12 pb-12 px-12">
						<text class="lines2 fs-28">{{ item.goodsTitle }}</text>
						<view class="fd-r ai-fe mt-24">
							<text class="c-red mb-4 fs-24">¥</text>
							<text class="c-red fs-36">
								{{ item.goodsPrice }}
							</text>
						</view>
					</view>
				</tm-waterfall-item>
			</tm-waterfall>
		</view>

		<view v-if="cartList.length > 0" class="w-750 h-92"></view>
		<view
			v-if="cartList.length > 0"
			class="z-foot px-24 py-16 bgc-white fd-r"
		>
			<checkbox
				color="#c8161d"
				:checked="checkedAll"
				style="transform: scale(0.7)"
				@click="HCheckAll"
			/>
			<text class="fs-28">全选</text>
			<block v-if="isManage">
				<view class="flex1 fd-r jc-fe">
					<button
						class="btn-red-plain w-200 h-60 lh-60 fs-28"
						@click="HBatchDel"
					>
						删除
					</button>
				</view>
			</block>
			<block v-else>
				<view class="flex1 pr-12 fd-c ai-fe">
					<view class="fd-r ai-fe">
						<text class="fs-28 c-grey">合计：</text>
						<text class="fs-28 c-red mb-4">￥</text>
						<text class="fs-36 c-red">{{ cartAmount }}</text>
					</view>
				</view>

				<button
					class="btn-red w-200 h-60 lh-60rpx fs-28"
					@click="gotoOrderAdd"
				>
					去结算
				</button>
			</block>
		</view>
	</view>

	<view v-else class="px-24 pt-360">
		<button class="btn-red" @click="HGotoLogin">请先登录</button>
	</view>

	<z-sku ref="skuR"></z-sku>
</template>
<script setup>
import { ref } from 'vue';
import tmNavbar from '@/tmui/components/tm-navbar/tm-navbar.vue'
import tmStepper from '@/tmui/components/tm-stepper/tm-stepper.vue'
import ZSku from '@/component/z-sku/z-sku.vue';

const wall = ref(null);

// 更新购物车
import { storeToRefs } from 'pinia';
import { useCartStore } from '@/store/cart.js';
const cartStore = useCartStore();
const { hasToken, cartList, cartAmount, checkedAll } = storeToRefs(cartStore);

import { onShow } from '@dcloudio/uni-app';
onShow(() => {
	const token = uni.getStorageSync('token');
	if (token) {
		cartStore.getCartList();
		hasToken.value = true;
	} else {
		hasToken.value = false;
	}
});

import toolLogin from '@/utils/login.js';
const HGotoLogin = () => {
	toolLogin.gotoLogin();
};

import cartApi from '@/api/cartApi.js';
const HCheckAll = () => {
	const params = {
		checked: !checkedAll.value,
		ids: []
	};

	cartList.value.forEach((v) => {
		v.list.forEach((subV) => {
			if (subV.checked !== params.checked) {
				params.ids.push(subV.id);
			}
		});
	});
	if (params.ids.length == 0) return;
	cartApi.check(params).then(() => {
		cartStore.getCartList();
	});
};
const HCheckChange = (item) => {
	const params = {
		checked: !item.checked,
		ids: []
	};
	item.list.forEach((v) => {
		if (v.checked !== params.checked) {
			params.ids.push(v.id);
		}
	});
	if (params.ids.length == 0) return;
	cartApi.check(params).then(() => {
		cartStore.getCartList();
	});
};

const HSubCheckChange = (item) => {
	const params = {
		checked: !item.checked,
		ids: [item.id]
	};
	cartApi.check(params).then(() => {
		cartStore.getCartList();
	});
};

const HCountChange = (e, item) => {
	const params = {
		id: item.id,
		quantity: e
	};
	cartApi.submit(params).then(() => {
		cartStore.getCartList();
	});
};

const skuR = ref(null);
const HSpecChange = (cart) => {
	skuR.value.open(cart);
};

// 推荐列表
import { onLoad, onReachBottom } from '@dcloudio/uni-app';
// import goodApi from '@/api/goodApi.js';
const goodList = ref([]);
const pageSize = 10;
const noMore = ref(false);
const recommendGoods = (refresh) => {
	if (refresh) {
		noMore.value = false;
	}
	if (noMore.value) return;
	const len = goodList.value.length;
	const pageNum = refresh ? 1 : Math.ceil(len / pageSize) + 1;
	const params = {
		pageNum,
		pageSize
	};
	goodApi.recommendGoods(params).then((res) => {
		const arr = res.data.list.map((v) => {
			v.mainImg = JSON.parse(v.goodsPicture)?.pictures[0];
			return v;
		});

		if (arr.length < pageSize) {
			noMore.value = true;
		}

		goodList.value = refresh ? arr : [...goodList.value, ...arr];
	});
};

const HGotoDetail = (goodId, skuId) => {
	uni.navigateTo({
		url: `/pages/zone1/goods/index?goodId=${goodId}&skuId=${skuId}`
	});
};

onLoad(() => {
	// recommendGoods();
});

onReachBottom(() => {
	// recommendGoods();
});

const isManage = ref(false);
const HBatchDel = () => {
	uni.showModal({
		title: '提示',
		content: '确定删除吗？',
		success: (res) => {
			if (res.confirm) {
				HDoDel();
			}
		}
	});
};
const HDoDel = () => {
	let ids = [];
	cartList.value.forEach((p) => {
		p.cartList.forEach((v) => {
			if (v.checked) {
				ids.push(v.id);
			}
		});
	});
	if (ids.length == 0) return;
	cartApi
		.deleteGoodBatch({
			deleteStatus: 1,
			ids
		})
		.then(() => {
			cartStore.getCartList();
		});
};

const gotoOrderAdd = () => {
	// 获取选中的数据
	const arr = [];
	cartList.value.forEach((v) => {
		v.list.forEach((p) => {
			if (p.checked) {
				arr.push(p);
			}
		});
	});

	// 获取skuId和购买数量
	const skuList = arr.map((v) => {
		return {
			cartId: v.id,
			skuId: v.skuId,
			quantity: v.quantity
		};
	});

	// 页面跳转并传递参数
	uni.navigateTo({
		url: '/pages/zone1/order/add/index',
		success: (res) => {
			res.eventChannel.emit('to-order-add', skuList);
		}
	});
};
</script>

<style scoped></style>
